package com.azxc.rapid.auth.endpoint;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.azxc.rapid.auth.config.JapConfigContext;
import com.azxc.rapid.auth.sso.Oauth2StrategyNew;
import com.azxc.rapid.auth.utils.CheckSign;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.feign.IUserClient;
import com.fujieid.jap.core.JapUser;
import com.fujieid.jap.core.JapUserService;
import com.fujieid.jap.core.result.JapResponse;
import com.fujieid.jap.http.adapter.jakarta.JakartaRequestAdapter;
import com.fujieid.jap.http.adapter.jakarta.JakartaResponseAdapter;
import com.fujieid.jap.oauth2.OAuthConfig;
import com.fujieid.jap.oauth2.Oauth2EndpointMethodType;
import com.fujieid.jap.oauth2.Oauth2GrantType;
import com.fujieid.jap.oauth2.Oauth2ResponseType;

import com.google.protobuf.ServiceException;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName : com.azxc.rapid.auth.endpoint.Oauth2RapidController
 * @Description : 请求统一认证平台
 * @Author : linym
 * Created by user on 2022-02-15 17:05:24
 */
@Slf4j
@RestController
@RequestMapping("/oauth2")
public class Oauth2RapidController implements InitializingBean {

	@Autowired
	private JapUserService japUserService;

	private Oauth2StrategyNew oauth2Strategy;

	@Autowired
	private IUserClient userClient;

	@RequestMapping("/login/rapid")
	public ModelAndView renderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException {
		JapConfigContext.strategy = "oauth2";
		OAuthConfig config = new OAuthConfig();
		String state= UuidUtils.getUUID();
		String callBackUrl="http://8.130.161.168:81/api/rapid-auth/oauth2/login/rapid";  //http://localhost:8100/oauth2/login/rapid
		String AuthorizationUrl="http://10.8.0.130:8090/rapid-sso/oauth/authorize?response_type=code&scope=read&redirect_uri=http://8.130.161.168:81/api/rapid-auth/oauth2/login/rapid&state="+state; //"http://localhost:8090/rapid-sso/oauth/authorize?response_type=code&scope=read&redirect_uri=http://localhost:8100/oauth2/login/rapid&state="+state
		String tokenUrl="http://10.8.0.130:8090/rapid-sso/oauth/token";//http://localhost:8090/rapid-sso/oauth/token
		String UserinfoUrl="http://10.8.0.130:8090/rapid-sso/oauth/getUserInfoDto";//http://localhost:8090/rapid-sso/oauth/getUserInfoDto
		config.setPlatform("test")
			.setState(state)
			.setClientId("d0317f3288")
			.setClientSecret("1614dfa7008241919e1bb7e76ea6f19f")
			.setCallbackUrl(callBackUrl)
			.setAccessTokenEndpointMethodType(Oauth2EndpointMethodType.GET)
			.setUserInfoEndpointMethodType(Oauth2EndpointMethodType.GET)
			.setAuthorizationUrl(AuthorizationUrl)
			//url后不需要带参数，参数会自动加上，多加会有bug
			.setTokenUrl(tokenUrl)
			.setUserinfoUrl(UserinfoUrl)
			.setGrantType(Oauth2GrantType.AUTHORIZATION_CODE)
			//这里设置会有bug，放到请求认证的地址中
			.setScopes(new String[]{"read"})
			.setResponseType(Oauth2ResponseType.CODE);
		JapResponse japResponse = oauth2Strategy.authenticate(config, new JakartaRequestAdapter(request), new JakartaResponseAdapter(response));
		if (japResponse.isSuccess() && !japResponse.isRedirectUrl()) {
			// 登录成功，需要对用户数据进行处理
			// ...
			System.out.println("登录成功！");
			//JSONObject jsonObject=JSONObject.(japResponse.getData());

			System.out.println(JSONObject.toJSONString(japResponse.getData()));

			//返回的业务appUserId
			String userId=((Map)((Map)((JapUser)japResponse.getData()).getAdditional()).get("data")).get("appUserId").toString();
			R<User> userR= userClient.userInfoById(Long.valueOf(userId));
			String url="http://localhost:8100/oauth/token";//http://localhost:8100/oauth/token
			url+="?tenantId=000000&username="+userR.getData().getAccount()+"&grant_type=sso&scope=all&type=account&uid="+userId;
			System.out.println("url:"+url);
			HttpRequest request2 = HttpUtil.createPost(url);
			request2.header("Tenant-Id", "000000");
			request2.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");

			HttpResponse response2 = request2.execute();
			String body = response2.body();
			log.debug("请求结果:"+body);
			JSONObject jsonObject=	JSONObject.parseObject(body);

			String atoken=jsonObject.getString("access_token");
			String rtoken=jsonObject.getString("refresh_token");
			//回调地址写死
			String	redirectUrl="http://192.168.0.56:1889/#/auth?saber-access-token="+atoken+"&saber-refresh-token="+rtoken;
			//创建Cookie
			Cookie cookie = new Cookie("saber-access-token", atoken);
			cookie.setPath("/");

			Cookie cookie2 = new Cookie("saber-refresh-token", rtoken);
			cookie2.setPath("/");

			System.out.println("atoken:"+atoken);
			System.out.println("rtoken:"+rtoken);
			//设置Cookie的最大生命周期,否则浏览器关闭后Cookie即失效
			//cookie.setMaxAge(Integer.MAX_VALUE);
			//将Cookie加到response中
			response.addCookie(cookie);
			response.addCookie(cookie2);

			return new ModelAndView(new RedirectView(redirectUrl));
		}
		if (!japResponse.isSuccess()) {
			throw new ServiceException(japResponse.getMessage());
			//return new ModelAndView(new RedirectView("/?error=" + URLUtil.encode(japResponse.getMessage())));
		}
		if (japResponse.isRedirectUrl()) {
			return new ModelAndView(new RedirectView((String) japResponse.getData()));
		} else {
			return new ModelAndView(new RedirectView("/"));
		}
	}

	private String buildGetUserInfo(String token){
		Long timestamp=System.currentTimeMillis();
		String url="http://localhost:8090/rapid-sso/oauth/getUserInfoDto?access_token="+token;
		url+="&timestamp="+timestamp;
		url+="&appId=d0317f3288";
		String sk="1614dfa7008241919e1bb7e76ea6f19f";
		String sign= CheckSign.getSign(sk,url);
		url+="&signature="+sign;
		System.out.println(url);
		return url;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		oauth2Strategy = new Oauth2StrategyNew(japUserService, JapConfigContext.getConfig());
	}

	/*public static void main(String[] args){
		String url="http://localhost:8100/oauth/token";//buildGetUserInfo( ((JapUser)japResponse.getData()).getToken());
		url+="?tenantId=000000&username=admin&grant_type=sso&scope=all&type=account&uid=1123598821738675201";
		HttpRequest request2 = HttpUtil.createPost(url);
		request2.header("Tenant-Id", "000000");
		request2.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");

		HttpResponse response2 = request2.execute();
		String body = response2.body();
		log.debug("请求结果:"+body);
	}*/
}
